package com.imist.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class IOServer {
    public static void main(String[] args) {
        try {
            final ServerSocket serverSocket = new ServerSocket(8000);
            //1. 接受新的连接线程
            new Thread(new Runnable() {
                public void run() {
                    while(true){
                        try {
                            //2.阻塞方法获取新的连接
                            final Socket socket = serverSocket.accept();
                            //3. 每一个新的连接都创建一个线程，负责读取数据；
                            new Thread(new Runnable() {
                                public void run() {
                                    int len = 0;
                                    byte[] data = new byte[1024];
                                    try {
                                        InputStream in = socket.getInputStream();
                                        while ((len = in.read(data) )!= -1){
                                            System.out.println(new String(data, 0, len));
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
